package com.zwcl.common.mq;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @Title: MessageUtils
 * @Description: 消息工具类
 * @date : 2020/11/4 15:15
 */
@Component
public class MessageUtils {

    @Autowired
    private MqKeyGenerator keyGenerator;

    public Message buildMessage(String msg){
        Message<String> message = MessageBuilder.withPayload(msg).build();
        return message;
    }

    public Message buildMessage(BasePayload payload) {
        payload.setBizId(keyGenerator.getBizOperationId());
        Message msg = MessageBuilder.withPayload(payload).build();
        return msg;
    }

    public Message buildMessage(BasePayload payload, String keys) {
        payload.setBizId(keyGenerator.getBizOperationId());
        MessageBuilder builder = getBuilder(payload, keys);

        return builder.build();
    }

    public  <T> Message<T> buildMessage(T message, String keys) {
        MessageBuilder<T> builder = MessageBuilder.withPayload(message);
        if (StringUtils.isNotEmpty(keys)) {
            builder.setHeader(RocketMQHeaders.KEYS, keys);
        }
        return builder.build();
    }

    public Message buildTransactionMessage(BasePayload payload, String keys, String transactionId) {
        payload.setBizId(keyGenerator.getBizOperationId());

        MessageBuilder builder = getBuilder(payload, keys);
        builder.setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId);

        return builder.build();
    }

    private MessageBuilder getBuilder(BasePayload payload, String keys){
        MessageBuilder<BasePayload> builder = MessageBuilder.withPayload(payload);
        if(StringUtils.isNotBlank(keys)){
            builder.setHeader(RocketMQHeaders.KEYS, keys);
        }
        return builder;
    }

}